package Collection;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

/**
 * @author 王艺锡
 * @version 1.0
 */
public class CollectionIterator {
    @SuppressWarnings({"all"})
    public static void main(String[] args) {
        Collection col = new ArrayList();
        col.add(new Book("鲁滨孙漂流记", "王艺锡", 159.2));
        col.add(new Book("三国演义", "罗贯中", 19.8));
        col.add(new Book("数据结构与算法", "刘涛", 39.9));

        System.out.println(col);

        //如何遍历col集合->先得到col对应的迭代器->使用while循环遍历
        Iterator iterator = col.iterator();
        int i = 1;
        //itit
        while (iterator.hasNext()) {

            Object obj = iterator.next();
            String format = String.format("第%d本书:" + obj, i);
            System.out.println(format);
            i++;
        }
        //当退出while循环后，如果想重新遍历集合，需要重置迭代器
        iterator = col.iterator();
        i = 1;
        while (iterator.hasNext()) {
            Object obj = iterator.next();
            String format = String.format("第%d本书:" + obj, i);
            System.out.println(format);
            i++;
        }


        //使用增强for遍历集合，增强for实质上用的是简化版的迭代器遍历
        //增强for快捷键“I”
        i = 1;
        System.out.println("======增强for=====");
        for (Object book : col) {
            String format = String.format("第%d本书:" + book, i);
            System.out.println(format);
            i++;
        }



    }

}


class Book {
    private String name;
    private String author;
    private double price;

    public Book(String name, String author, double price) {
        this.name = name;
        this.author = author;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                ", author='" + author + '\'' +
                ", price=" + price +
                '}';
    }
}
